package com.kongchengji.zhanguafou.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PingServerUtil {
    /**
     * 调用系统命令ping服务器
     * @param ip 服务器ip
     * @return 返回包装好的map数据
     */
    public static Map pingServer(String ip){
        BufferedReader in = null;
        String[] cmds = {"ping","-c","4","-w","4",ip};
        ProcessBuilder pb=new ProcessBuilder(cmds);
        pb.redirectErrorStream(true);
        Process p;
        Map<String,String> map = new HashMap();
        try {
            //执行命令并获取输出
//            Process p = r.exec(pingCommand);
            p = pb.start();
            in = new BufferedReader(new InputStreamReader(p.getInputStream(),"gbk"));
            String line;
            while ((line = in.readLine()) != null) {
                //发送包的个数
                String packets = matchLine(line,"\\d+\\s*(?=packets)");
                if(packets !=null){
                    map.put("packets",packets);
                }
                //收到包的个数
                String received = matchLine(line,"\\d+\\s*(?=received)");
                if(received != null){
                    map.put("received",received);
                }
                //丢包率
                String lossRatio = matchLine(line,"\\d+%\\s*(?=packet)");
                if(lossRatio != null){
                    map.put("lossRation",lossRatio);
                }
                //连接最小时间,平均时间，最大时间，算术平均差
                String time = matchLine(line,"(?<=min/avg/max/mdev).*");
                if(time != null){
                    map.put("time",time);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace(); //出现异常则返回假
        } finally {
            try {
                if(in != null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    /**
     * 根据规则返回匹配的结果
     * @param line 匹配的内容
     * @param regex 匹配的规则
     * @return 返回匹配结果
     */
    private static String matchLine(String line,String regex){
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(line);
        if(m.find()){
            return m.group();
        }
        return null;
    }
}
